package com.data.modules.quartz.job;

import cn.hutool.core.collection.CollectionUtil;
import com.data.common.system.vo.DictModel;
import com.data.modules.system.entity.RptLeaveEmp;
import com.data.modules.system.mapper.RptLeaveEmpMapper;
import com.data.modules.system.service.ISysDictService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * 离职劳动者统计
 *
 * @author: pys
 * @since: 2022-04-02 16:42
 **/

@Component
@Slf4j
public class LeaveCensusJob implements Job {

    @Autowired
    RptLeaveEmpMapper rptLeaveEmpMapper;

    @Autowired
    private ISysDictService iSysDictService;

    private final static String BEGIN_TIME="2022-01-01";

    private final static String PREFIX="iot_";


    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {

        //拿到当前环境iot库名
        List<DictModel> iotEnvironment = iSysDictService.queryDictItemsByCode("iot_environment");

        if (CollectionUtil.isEmpty(iotEnvironment)){
            log.debug("离职统计环境配置为空");
            return;
        }

        String environment = PREFIX+iotEnvironment.get(0).getValue();
        //查出数据
        List<RptLeaveEmp> rptLeaveEmps = selectInfo(BEGIN_TIME,environment);

        //清空表
        truncate();

        //批量插入
        batchInsert(rptLeaveEmps);

    }

    private void batchInsert(List<RptLeaveEmp> rptLeaveEmps) {
        rptLeaveEmps.stream().forEach(rptLeaveEmp -> {
            rptLeaveEmp.setCreateTime(new Date());
            try {
                rptLeaveEmpMapper.insert(rptLeaveEmp);
            } catch (Exception e) {
                log.error("======插入离职表失败====",e);
            }
        });
    }

    private List<RptLeaveEmp> selectInfo(String beginTime,String environment) {
        return rptLeaveEmpMapper.queryCensusInfo(beginTime,environment);
    }

    private void truncate() {
        rptLeaveEmpMapper.truncateTable();
    }


}
